package com.utils;

import java.util.Map;
import java.util.Set;

import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.Validator;
import javax.validation.ValidatorFactory;

public class ValidatorUtils
{
    private static ValidatorFactory validatorFactory;
    private static Validator validator;
    
    static
    {
        validatorFactory=Validation.buildDefaultValidatorFactory();
        validator = validatorFactory.getValidator();
    }
    
    private static  ValidatorUtils validatorUtils = new ValidatorUtils();
    private ValidatorUtils(){}
    
    public static ValidatorUtils getInstance()
    {
        return validatorUtils;
    }
    public static  <T> void valid(T formBean,Map<String, Object> model)
    {
        Set<ConstraintViolation<T>> set = validator.validate(formBean);
        if(set.isEmpty())
        {
            return;
        }
        for (ConstraintViolation<T> constraintViolation : set)
        {
            String key =constraintViolation.getPropertyPath()+"Error";
            if(model.containsKey(key))
            {
                Object oldVal = model.get(key);
                model.remove(key);
                
                model.put(key, oldVal);
            }
            else
            {
                model.put(key, constraintViolation.getMessage());
            }
           
        }
    }
}
